package com.gears_software.bbnetwork.utlis;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class ImageFileCache {
	// SD卡上图片储存地址
    private final static String path = Environment.getExternalStorageDirectory()
            .getPath() + "/bbnetword";
    
	public static void saveFile(Bitmap bitmap,String url){
		 try {
	            // 获得文件名字
	            final String fileNa = url.substring(url.lastIndexOf("/") + 1,
	                    url.length()).toLowerCase();
	            File file = new File(path + "/image/" + fileNa);
	            // 创建图片缓存文件夹
	            boolean sdCardExist = Environment.getExternalStorageState().equals(
	                    android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
	            if (sdCardExist) {
	                File maiduo = new File(path);
	                File ad = new File(path + "/image");
	                // 如果文件夹不存在
	                if (!maiduo.exists()) {
	                    // 按照指定的路径创建文件夹
	                    maiduo.mkdir();
	                    // 如果文件夹不存在
	                } else if (!ad.exists()) {
	                    // 按照指定的路径创建文件夹
	                    ad.mkdir();
	                }
	                // 检查图片是否存在
	                if (!file.exists()) {
	                    file.createNewFile();
	                }
	            }
	            BufferedOutputStream bos = new BufferedOutputStream(
	                    new FileOutputStream(file));
	            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
	            bos.flush();
	            bos.close();
	        } catch (Exception e) {
	            // TODO: handle exception
	        }
	}
	
	public static Bitmap getFileImage(String imageUrl){
		 Bitmap bmpDefaultPic = null;
		 
	        // 获得文件路径
	        String imageSDCardPath = path
	                + "/image/"
	                + imageUrl.substring(imageUrl.lastIndexOf("/") + 1,
	                        imageUrl.length()).toLowerCase();
	        File file = new File(imageSDCardPath);
	        // 检查图片是否存在
	        if (!file.exists()) {
	            return null;
	        }
	        bmpDefaultPic = BitmapFactory.decodeFile(imageSDCardPath, null);
	 
	        if (bmpDefaultPic != null&&bmpDefaultPic.toString().length() > 3) {
	            return bmpDefaultPic;
	        } else
	            return null;
	}
}
